//
//  SeekWebViewController.m
//  cityCar
//
//  Created by 刘伟 on 14-11-1.
//  Copyright (c) 2014年 lanou3g.com 蓝鸥科技. All rights reserved.
//

#import "SeekWebViewController.h"
#import "SeekCarViewController.h"
#import "SeekSelectViewController.h"
#import "DataBaseHandler.h"
#import "Car.h"

@interface SeekWebViewController ()<UIScrollViewDelegate, UIWebViewDelegate>
//@property(nonatomic, retain)UISegmentedControl *segment;
// 报价的 webview
@property(nonatomic, retain)UIWebView *myWeb;

// 收藏的label
@property(nonatomic, retain)UILabel *collectLabel;
// 收藏的button
@property(nonatomic, retain)UIButton *collectButton;
// 加载
@property(nonatomic, retain)LoadingView *load;
@end

@implementation SeekWebViewController

- (void)dealloc
{
    [_scrollView release];
    [_myWeb release];
    [_load release];
    [_collectButton release];
    [_collectLabel release];
    [_Idurl release];
    [_car release];
    [super dealloc];
}

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        
        self.car = [[Car alloc] init];
        [_car release];
    }
    return self;
}
- (void)viewDidLoad
{
    [super viewDidLoad];

    self.view.backgroundColor = [WebColor white];
    self.automaticallyAdjustsScrollViewInsets = NO;
    [self.navigationController setNavigationBarHidden:YES];
    self.tabBarController.tabBar.hidden = YES;
    
    self.myWeb = [[UIWebView alloc] initWithFrame:CGRectMake(0, -40, self.view.frame.size.width, self.view.frame.size.height + 140)];
    NSURL *url = [NSURL URLWithString:self.Idurl];
    NSURLRequest *request = [[NSURLRequest alloc] initWithURL:url];
    self.myWeb.scrollView.showsVerticalScrollIndicator = NO;
    [self.myWeb loadRequest:request];
    [self.myWeb setUserInteractionEnabled:YES];
    self.myWeb.delegate = self;
    self.myWeb.scrollView.bounces = NO;
    [self.view addSubview:self.myWeb];
    // 把一个view视图放到最后面
    [self.view sendSubviewToBack:self.myWeb];
    [_myWeb release];
    
    [self setupView];
    
    self.load= [[LoadingView alloc]initWithFrame:self.view.bounds];
    [self.view addSubview:_load];
    [self.view bringSubviewToFront:_load];
    [_load release];
    
    // 监听网络状态
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reachabilityChanged:) name: kReachabilityChangedNotification object: nil];
    Reachability *hostReach = [Reachability reachabilityWithHostName:@"www.google.com"];//可以以多种形式初始化
    [hostReach startNotifier];
    
}
#pragma mark 判断网络状态
// 连接改变
- (void) reachabilityChanged: (NSNotification* )note
{
    Reachability* curReach = [note object];
    NSParameterAssert([curReach isKindOfClass: [Reachability class]]);
    [self updateInterfaceWithReachability: curReach];
}

//处理连接改变后的情况
- (void) updateInterfaceWithReachability: (Reachability*) curReach
{
    //对连接改变做出响应的处理动作。
    NetworkStatus status = [curReach currentReachabilityStatus];
    
    if (status != NotReachable) {
        NSURL *url = [NSURL URLWithString:self.Idurl];
        NSURLRequest *request = [[NSURLRequest alloc] initWithURL:url];
        [self.myWeb loadRequest:request];
    }
    
}

#pragma mark -


// 视图又出现
- (void)viewDidAppear:(BOOL)animated
{
    [self settingButton];
}

- (void)setupView
{
    // 视图控制器的宽和高
    CGFloat x = self.view.frame.size.width;
    
    UIView *topView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 64)];
    topView.backgroundColor = [WebColor whiteSmoke];
    [self.view addSubview:topView];
    [topView release];
    
    UILabel *headLabel = [[UILabel alloc] initWithFrame:CGRectMake((x - 60) / 2, 15, 60, 50)];
    headLabel.text = @"详情";
    headLabel.textAlignment = NSTextAlignmentCenter;
    [topView addSubview:headLabel];
    [headLabel release];
    
    // 返回按钮
    UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    [button setBackgroundImage:[UIImage imageNamed:@"iconfont-fanhui.png"] forState:UIControlStateNormal];
    [button addTarget:self action:@selector(buttonClicked:) forControlEvents:UIControlEventTouchUpInside];
    button.frame = CGRectMake(10, 25, 30, 30);
    [topView addSubview:button];
    
    UIView *followingView = [[UIView alloc] initWithFrame:CGRectMake(0, self.view.frame.size.height - 49, self.view.frame.size.width, 49)];
    followingView.backgroundColor = [WebColor whiteSmoke];
    [self.view addSubview:followingView];
    
    UIButton *back = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    back.tag = 9546;
    [back setBackgroundImage:[UIImage imageNamed:@"back.png"] forState:UIControlStateNormal];
    [back addTarget:self action:@selector(forwardAndBackAction:) forControlEvents:UIControlEventTouchUpInside];
    back.frame = CGRectMake(20, 7, 30, 30);
    [followingView addSubview:back];
    
    UIButton *forward = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    [forward setBackgroundImage:[UIImage imageNamed:@"forward.png"] forState:UIControlStateNormal];
    [forward addTarget:self action:@selector(forwardAndBackAction:) forControlEvents:UIControlEventTouchUpInside];
    forward.frame = CGRectMake(self.view.frame.size.width - 50, 7, 30, 30);
    [followingView addSubview:forward];

    
    // 收藏按钮
    // 收藏
    self.collectButton = [UIButton buttonWithType:UIButtonTypeSystem];
    self.collectButton.frame = CGRectMake(x - 40, 25, 30, 30);
    [self.collectButton setBackgroundImage:[UIImage imageNamed:@"iconfont-shoucang-3.png"] forState:UIControlStateNormal];
    [self.collectButton addTarget:self action:@selector(collectButtonClicked:) forControlEvents:UIControlEventTouchUpInside];
    self.collectButton.tintColor = [WebColor black];
    [topView addSubview:self.collectButton];
    
    // 显示收藏的label
    self.collectLabel = [[UILabel alloc] initWithFrame:CGRectMake((x - 100) / 2, 200, 100, 30)];
    self.collectLabel.hidden = YES;
    self.collectLabel.textColor = [WebColor white];
    self.collectLabel.alpha = 0.5;
    self.collectLabel.backgroundColor = [WebColor black];
    self.collectLabel.textAlignment = NSTextAlignmentCenter;
    [self.view addSubview:self.collectLabel];
    [_collectLabel release];
    
    [NSTimer scheduledTimerWithTimeInterval:2 target:self selector:@selector(cartoon) userInfo:nil repeats:YES];

}

// 前进后退方法
- (void)forwardAndBackAction:(UIButton *)Button
{
    switch (Button.tag) {
        case 9546:
        {
            [_myWeb goBack];
        }
            break;
        default:
        {
            [_myWeb goForward];
        }
            break;
    }
}

// 点击收藏
- (void)collectButtonClicked:(UIButton *)button
{
    DataBaseHandler *handler = [DataBaseHandler shareInstrance];
    
    UIImage *image = [UIImage imageNamed:@"iconfont-shoucang-3.png"];
    UIImage *buttonImage = [button backgroundImageForState:UIControlStateNormal];
    if ([buttonImage isEqual:image]) {
        [button setBackgroundImage:[UIImage imageNamed:@"iconfont-shoucang-4.png"] forState:UIControlStateNormal];
        self.collectLabel.hidden = NO;
        self.collectLabel.text = @"收藏成功";
        [self.view bringSubviewToFront:self.collectLabel];
        
        // 创建表
        [handler createTableWeb];
        
        // model类
        ForumGather *forum = [[ForumGather alloc] init];
        forum.name = self.car.name;
        forum.Id = self.car.Id;
        forum.image = self.car.logo;
        forum.url = self.Idurl;
        
        // 添加表
        [handler insertWeb:forum];
        [forum release];
        
        
    } else {
        [button setBackgroundImage:[UIImage imageNamed:@"iconfont-shoucang-3.png"] forState:UIControlStateNormal];
        self.collectLabel.hidden = NO;
        self.collectLabel.text = @"取消收藏";
        [self.view bringSubviewToFront:self.collectLabel];
        [handler deleteWeb:self.car.Id];
    }
}

// 设置button的背景色
- (void)settingButton
{
    DataBaseHandler *handler = [DataBaseHandler shareInstrance];
    NSString *string = [NSString stringWithFormat:@"%@", self.car.Id];
    for (ForumGather *fav in [handler selectWebAll]) {
        if ([string isEqualToString:fav.Id]) {
            [self.collectButton setBackgroundImage:[UIImage imageNamed:@"iconfont-shoucang-4.png"] forState:UIControlStateNormal];
            break;
        } else {
            [self.collectButton setBackgroundImage:[UIImage imageNamed:@"iconfont-shoucang-3.png"] forState:UIControlStateNormal];
        }
    }
}


// 收藏自动取消
- (void)cartoon
{
    self.collectLabel.hidden = YES;
}


//返回
- (void)buttonClicked:(UIButton *)button
{
    [self.navigationController popViewControllerAnimated:YES];
    
    if ([[self.navigationController.viewControllers lastObject] class] == [SeekSelectViewController class]) {
        [self.navigationController setNavigationBarHidden:YES];
        self.tabBarController.tabBar.hidden = YES;
    } else{
        [self.navigationController setNavigationBarHidden:NO];
        self.tabBarController.tabBar.hidden = NO;
    }
    [self dismissViewControllerAnimated:YES completion:nil];
}

#pragma mark - webView协议
// 允许用户点击，网页自动响应
//- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request
// navigationType:(UIWebViewNavigationType)navigationType
//{
//    if ( navigationType == UIWebViewNavigationTypeLinkClicked ) {
//        [[UIApplication sharedApplication] openURL:[request URL]];
//        return NO;
//    }
//    return YES;
//}

- (void)webViewDidFinishLoad:(UIWebView *)webView
{
    [_load removeFromSuperview];
}

- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error
{
    
}
#pragma mark -
- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
